import axios from 'axios'
import { useUserStore } from '@/stores/user'

// 简单的消息提示函数
const showMessage = (message, type = 'error') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'error' ? 'bg-red-500' : 
    type === 'warning' ? 'bg-yellow-500' : 
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)
  
  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

// 创建axios实例
const request = axios.create({
  baseURL: 'http://localhost:8082/api',
  timeout: 10000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // 如果是blob响应（文件下载），直接返回
    if (response.config.responseType === 'blob') {
      return response
    }
    
    const res = response.data
    
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    if (res.code === 200) {
      return res
    } else {
      // 否则的话抛出错误
      showMessage(res.message || '请求失败', 'error')
      return Promise.reject(new Error(res.message || '请求失败'))
    }
  },
  error => {
    console.error('响应错误:', error)
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          showMessage('未授权，请重新登录', 'error')
          const userStore = useUserStore()
          userStore.logout()
          break
        case 403:
          showMessage('权限不足', 'error')
          break
        case 404:
          showMessage('请求的资源不存在', 'error')
          break
        case 500:
          showMessage('服务器内部错误', 'error')
          break
        default:
          showMessage(data?.message || '请求失败', 'error')
      }
    } else {
      showMessage('网络错误，请检查网络连接', 'error')
    }
    
    return Promise.reject(error)
  }
)

export default request
